import React, { useState, useEffect, useMemo } from 'react';
import { withRouter } from 'react-router';
import PropTypes from 'prop-types';
import cn from 'classnames';
import Breadcrumb, { Item } from '../../../components/Breadcrumb';
import HostSearchInput from '../../../components/HostSearchInput';
import Button from '@kuiper-components/button';
import { Table, searchStringBuilder } from '@kuiper-components/page-table';
import Dialog from '@kuiper-components/dialog';
import Loading from '@kuiper-components/loading';
import notification from '@kuiper-components/notification';
import Select, { Option } from '@kuiper-components/select';
import { Warning32 as Warn } from '@carbon/icons-react';
import fetch from 'API/fetch';
import s from './style.module.css';
import end from './end.svg';
import success from './suc.svg';
import error from './err.svg';
import Tooltip from '@kuiper-components/tooltip';
const typeImg = {
	success,
	error,
};
function Ipset({ history, location }) {
	const [selectedRows, setSelectedRows] = useState({});
	const [ipVisible, setIpVisible] = useState(false);
	const [scanIp, setScanIp] = useState({ IPv4: [], IPv6: [] });
	const [delVisible, setDelVisible] = useState(false);
	const [limitVisible, setLimitVisible] = useState(false);
	const [oneKeyVisible, setOneKeyVisible] = useState(false);
	const [addVisible, setAddVisible] = useState(false);
	const [assetName, setAssetName] = useState('');
	const [assetId, setAssetId] = useState('');
	const [pageTotal, setPageTotal] = useState(0);
	const [dataNum, setDataNum] = useState({ total: 0, success: 0, error: 0 });
	const [data, setData] = useState([]);
	const [assetNameArr, setAssetNameArr] = useState([]);
	const [nodata, setNoData] = useState([]);
	const [result, setResult] = useState([]);
	const [delId, setDelId] = useState([]);
	const [addressData, setAddressData] = useState([]);
	const [loading, setLoading] = useState(true);
	const [addTip, setAddTip] = useState(null);
	const enableBatchDelete = Object.values(selectedRows).some(Boolean);
	const search = new URLSearchParams(location.search);
	const searchKey = search.get('searchKey') ? search.get('searchKey') : '';
	const columns = [
		{ title: '资产名称', dataIndex: 'name', key: 'name' },
		{ title: '资产地址', dataIndex: 'targetUrl', key: 'targetUrl' },
		{
			title: '加白IP类型',
			dataIndex: 'ip_whitelist_type',
			key: 'ip_whitelist_type',
			render(e) {
				return (
					<div className={s.ipType}>
						<img classNames="statusImg" src={end} alt="" />
						<span>{e[0]}</span>
						{e[1] && <span>{e[1]}</span>}
					</div>
				);
			},
		},
		{
			title: '操作',
			dataIndex: '_id',
			key: '_id',
			render(_id) {
				return (
					<>
						<span className={s.del} onClick={() => delClick(_id)}>
							删除
						</span>
					</>
				);
			},
		},
	];
	// 获取列表
	const errorList = useMemo(() => {
		const arr = [];
		result.forEach(item => {
			if (item.status === 'error') {
				arr.push(item);
			}
		});
		return arr;
	}, [result]);
	const destory = () => {
		setLimitVisible(false);
		window.location.reload();
	};
	const delBatch = () => {
		setDelVisible(false);
		setSelectedRows({});
	};
	useEffect(() => {
		getTableData(searchKey);
	}, []);
	// 请求方法
	function getTableData(param = '') {
		setLoading(true);
		let url = `/api/v2/cloud/idw_get_assets`;
		if (param) {
			url = `/api/v2/cloud/idw_get_assets?searchKey=${param}&page=1`;
		}
		try {
			fetch(url, {
				method: 'GET',
			})
				.then(res => {
					if (res.code === 200) {
						setLoading(false);
						setScanIp({
							IPv4: res.results.scanner_ipv4 || [],
							IPv6: res.results.scanner_ipv6 || [],
						});
						setPageTotal(res.results.count);
						setData(res.results.assets);
						setNoData(res.results.not_added);
					}
				})
				.catch(e => {
					notification.error({
						message: e.message,
						placement: 'top',
					});
				});
		} catch (err) {}
	}
	function getReq(type, data) {
		try {
			return fetch('/api/v2/cloud/idw_action', {
				method: type,
				body: data,
			})
				.then(res => {
					if (res.results.failed) {
						setAddTip(
							<div className={s.dioTip}>
								<p>
									<img src={typeImg[res.results.info[0].status]}></img>
									{res.results.info[0].msg}
								</p>
								<p>
									<img src={typeImg[res.results.info[1].status]}></img>
									{res.results.info[1].msg}
								</p>
								<span
									onClick={() => {
										setAddTip(null);
									}}
								>
									×
								</span>
							</div>
						);
						setTimeout(() => {
							setAddTip(null);
						}, 3000);
					} else {
						notification.success({
							message: res.results.info[0].msg,
							placement: 'top',
						});
						setAddVisible(false);
						setDelVisible(false);
						getTable();
					}
				})
				.catch(e => {
					notification.error({
						message: e.message,
						placement: 'top',
					});
				});
		} catch (err) {}
	}
	// 添加
	const addOne = () => {
		const data = JSON.stringify({
			action: 'add',
			assetIds: [assetId],
		});
		if (!assetId) {
			notification.error({
				placement: 'top',
				message: '请选择资产地址',
			});
			return;
		}
		return getReq('POST', data);
	};
	// 删除
	const delClick = val => {
		setDelVisible(true);
		if (val === 'batch') {
			const arr = Object.keys(selectedRows);
			setDelId([].concat(arr));
		} else {
			setDelId([].concat(val));
		}
	};
	const delItem = () => {
		const data = JSON.stringify({
			action: 'delete',
			assetIds: delId,
		});
		return getReq('POST', data);
	};
	// 一键添加
	const oneKeyAdd = () => {
		const arr = [];
		nodata.forEach(item => {
			arr.push(item._id);
		});
		try {
			return fetch('/api/v2/cloud/idw_action', {
				method: 'POST',
				body: JSON.stringify({ action: 'add', assetIds: arr }),
			})
				.then(res => {
					if (res.code === 200) {
						setResult(res.results.info);
						setDataNum({
							total: res.results.total,
							success: res.results.success,
							error: res.results.failed,
						});
						setOneKeyVisible(false);
						setLimitVisible(true);
					}
				})
				.catch(e => {
					notification.error({
						message: e.message,
						placement: 'top',
					});
				});
		} catch (err) {}
	};
	const assetChange = e => {
		setAssetName(e);
		setAssetId('');
		setAddressData(nodata.filter(item => item.name === e));
	};
	const changePage = (val, size) => {
		setLoading(true);
		const url = `/api/v2/cloud/idw_get_assets?page=${val}&pageSize=${size}&searchKey=${searchKey}`;
		fetch(url, {
			method: 'GET',
		}).then(res => {
			if (res.code === 200) {
				setLoading(false);
				setScanIp({
					IPv4: res.results.scanner_ipv4 || [],
					IPv6: res.results.scanner_ipv6 || [],
				});
				setPageTotal(res.results.count);
				setData(res.results.assets);
				setNoData(res.results.not_added);
			}
		});
	};
	const addressChange = e => {
		setAssetId(e);
	};
	const getTable = val => {
		const routePrefix = '/yfld/whitelist';
		const search = searchStringBuilder(location.search, {
			searchKey: val || '',
			page: 1,
		});
		history.replace(`${routePrefix}?${search}`);
		// setSearchKey(val);
		setSelectedRows({});
		getTableData(val || '');
	};
	const handleRowSelectionChange = row => {
		setSelectedRows(row);
	};
	const openAddDialog = () => {
		const map = new Map();
		nodata.forEach(item => {
			if (!map.has(item.name)) {
				map.set(item.name, item);
			}
		});
		const value = [...map.values()];
		setAssetNameArr(value);
		setAddVisible(true);
		setAssetName('');
		setAssetId('');
	};

	return (
		<div className={s.content}>
			<Breadcrumb className={s.bread}>
				<Item key="yfld">云防联动</Item>
				<Item key="">功能设置</Item>
				<Item>扫描器IP加白</Item>
			</Breadcrumb>
			<div className={s.inner}>
				<p>
					<span className={s.icon}></span>
					<span className={s.tit}>扫描器IP加白</span>
					<span className={s.info}>
						以下资产将联动云防御白名单功能，对ScanV
						出口IP加白，避免因云防御防火墙拦截而无法扫描监测。
						<span
							className={s.DialogIp}
							onClick={() => {
								setIpVisible(true);
							}}
						>
							查看扫描器IP
						</span>
					</span>
				</p>
				<div className={s.searchBar}>
					<div>
						<Button primary onClick={openAddDialog}>
							添加
						</Button>
						<Button className={s.onekey} onClick={() => setOneKeyVisible(true)}>
							一键添加
						</Button>
					</div>
					<div>
						<HostSearchInput
							placeholder="请输入搜索内容"
							onChange={getTable}
							value={searchKey}
						/>
					</div>
				</div>
				<Loading show={loading}>
					<div>
						<Table
							routePrefix=""
							columns={columns}
							type="local"
							data={data}
							total={pageTotal}
							location={location}
							history={history}
							pagination={{
								showSizeChanger: false,
								pageSize: 10,
								total: pageTotal,
								onChange: changePage,
							}}
							rowSelected={selectedRows}
							onRowSelectionChange={handleRowSelectionChange}
							rightBottomContent={
								<Button
									className={s.linkBtn}
									link
									primary
									disabled={!enableBatchDelete}
									onClick={() => delClick('batch')}
								>
									批量删除
								</Button>
							}
						/>
					</div>
				</Loading>
				{/* 加白IPle类型 */}
				<Dialog
					title="扫描器IP地址"
					className={s.deldia}
					visible={ipVisible}
					onClose={() => {
						setIpVisible(false);
					}}
					destroyOnClose={true}
				>
					<div className={s.cont}>
						<div className={s.cont2}>
							<p className={s.ipTypeP}>
								<span>IPv4:</span>
								<span>182.140.244.222</span>
							</p>
							<p className={s.ipTypeP}>
								<span>IPv6:</span>
								<span>240e:d9:a003:1602::/64</span>
							</p>
						</div>
						<div className={s.footer}>
							<Button
								primary
								onClick={() => {
									setIpVisible(false);
								}}
							>
								确定
							</Button>
						</div>
					</div>
				</Dialog>
				<Dialog
					title="提示"
					className={s.deldia}
					visible={delVisible}
					destroyOnClose={true}
					onClose={() => delBatch(false)}
				>
					<div className={cn(s.cont, s.w350)}>
						<Warn className={s.warns} />
						<p>
							删除选中资产将同步删除其在知道创宇云防御平台IP白名单功能里设置的ScanV
							出口IP。您确定要删除吗？
						</p>
						<div className={s.footer}>
							<Button className={s.cancel} onClick={() => delBatch(false)}>
								取消
							</Button>
							<Button primary className={s.dels} onClick={delItem}>
								确定
							</Button>
						</div>
					</div>
				</Dialog>
				<Dialog
					title="添加"
					className={s.adddia}
					visible={addVisible}
					onClose={() => setAddVisible(false)}
				>
					<div className={s.cont}>
						<div className={s.selec}>
							<span>资产名称：</span>
							<Select
								value={assetName || undefined}
								placeholder="请选择资产名称"
								className={s.item}
								onChange={val => assetChange(val)}
							>
								{assetNameArr.map(item => (
									<Option key={item.name} value={item.name}>
										{item.name}
									</Option>
								))}
							</Select>
						</div>
						<div className={cn(s.selec, s.mt20)}>
							<span>资产地址：</span>
							<Select
								value={assetId || undefined}
								placeholder="请选择资产地址"
								className={s.item}
								onChange={val => addressChange(val)}
							>
								{addressData.map(item => (
									<Option key={item.targetUrl} value={item._id}>
										{item.targetUrl}
									</Option>
								))}
							</Select>
						</div>
						<p className={cn(s.selec, s.infowarn, s.mt20)}>
							请确保该资产在云防御处于云端防护模式，若为回源模式，添加的ScanV出口IP将不生效。
						</p>
						<div className={s.footer}>
							<Button className={s.cancel} onClick={() => setAddVisible(false)}>
								取消
							</Button>
							<Button primary className={s.dels} onClick={addOne}>
								添加
							</Button>
						</div>
						{addTip}
					</div>
				</Dialog>
				<Dialog
					title="提示"
					className={s.deldia}
					visible={oneKeyVisible}
					onClose={() => setOneKeyVisible(false)}
				>
					<div className={cn(s.cont, s.w350)}>
						<Warn className={s.warns} />
						<p>
							ScanV
							将自动探测该账号下同时接入监测及防御平台的资产，将扫描出口IP直接同步到云防御平台白名单里。
						</p>
						<p className={s.infowarn}>
							请确保资产在云防御处于云端防护模式，若为回源模式，添加的ScanV出口IP将不生效。
						</p>
						<div className={s.footer}>
							<Button
								className={s.cancel}
								onClick={() => setOneKeyVisible(false)}
							>
								取消
							</Button>
							<Button primary className={s.dels} onClick={oneKeyAdd}>
								一键添加
							</Button>
						</div>
					</div>
				</Dialog>
				<Dialog
					title="出口IP添加结果"
					className={s.deldia}
					visible={limitVisible}
					onClose={destory}
					destroyOnClose={true}
				>
					<div className={s.cont}>
						<p>
							<span>总计：{dataNum.total}</span>
							<span>成功：{dataNum.success}</span>
							<span>失败：{dataNum.error}</span>
						</p>
						<ul className={s.error}>
							<li>
								<span>资产名称</span>
								<span>资产地址</span>
								<span>失败原因</span>
							</li>
							{errorList.length ? (
								errorList.map((item, index) => (
									<li key={index}>
										<span className={s.ell} title={item.name}>
											{item.name}
										</span>
										<span className={s.ell} title={item.targetUrl}>
											{item.targetUrl}
										</span>
										<Tooltip placement="top" overlay={item.msg}>
											<span className={s.ell} title={item.msg}>
												{item.msg}
											</span>
										</Tooltip>
									</li>
								))
							) : (
								<li className={s.jcc}>暂无数据</li>
							)}
						</ul>
						<div className={s.footer}>
							<Button primary onClick={destory}>
								确定
							</Button>
						</div>
					</div>
				</Dialog>
			</div>
		</div>
	);
}
Ipset.propTypes = {
	location: PropTypes.shape({
		search: PropTypes.string.isRequired,
	}).isRequired,
	history: PropTypes.shape({
		replace: PropTypes.func.isRequired,
	}).isRequired,
};
export default withRouter(Ipset);
